import cv2 as cv
import sys
import os
from python_ai.common.xcommon import *
import matplotlib.pyplot as plt
import numpy as np
import time
import datetime


def my_show_img(img, title="no title", trans=None, **kwargs):
    global spn
    spn += 1
    plt.subplot(spr, spc, spn)
    if trans is not None:
        img = trans(img)
    plt.imshow(img, **kwargs)
    plt.axis('off')
    plt.title(title)


img_dir = '../../../../large_data/CV2/lesson/Day03'
img_name = '4perspective.jpg'
img_path1 = os.path.join(img_dir, img_name)

spr = 2
spc = 2
spn = 0
plt.figure(figsize=[8, 7])

sep('load')
img = cv.imread(img_path1, cv.IMREAD_COLOR)
print('original shape', img.shape)
H, W, _ = img.shape
H2 = (H - 1) // 2
W2 = (W - 1) // 2
my_show_img(img, 'original', lambda x: cv.cvtColor(x, cv.COLOR_BGR2RGB))

sep('Points and lines')


def my_set_point(x, y):
    global img
    img = cv.circle(img, (x, y), 50, (0, 255, 0), -1)

pt1 = (2481, 21)
pt2 = (3905, 373)
pt3 = (2501, 2237)
pt4 = (3885, 1621)
my_set_point(*pt1)
my_set_point(*pt2)
my_set_point(*pt3)
my_set_point(*pt4)
THICK = 20
img = cv.line(img, (W2, 0), (W2, H), (0, 255, 0), THICK)  # CENTER v
img = cv.line(img, (0, H2), (W, H2), (0, 255, 0), THICK)  # CENTER h
# other v
img = cv.line(img, (W2 // 2, 0), (W2 // 2, H), (0, 255, 0), THICK)
img = cv.line(img, (W2 // 2 + W2, 0), (W2 // 2 + W2, H), (0, 255, 0), THICK)
# other h
img = cv.line(img, (0, H2 // 2), (W, H2 // 2), (0, 255, 0), THICK)
img = cv.line(img, (0, H2 // 2 + H2), (W, H2 // 2 + H2), (0, 255, 0), THICK)
my_show_img(img, 'Points and lines', lambda x: cv.cvtColor(x, cv.COLOR_BGR2RGB))

sep('transform')
pts1 = np.float32([pt1, pt2, pt3, pt4])
pts2 = np.float32([(0, 0), (W, 0), (0, H), (W, H)])
M = cv.getPerspectiveTransform(pts1, pts2)
print('M:')
print(M)
dst = cv.warpPerspective(img, M, (W, H))
my_show_img(dst, 'Transformed', lambda x: cv.cvtColor(x, cv.COLOR_BGR2RGB))